Posted August 6, 2007
Something’s been bothering me for a while about Rails models. Instead of talking about the bother immediately, though, I’d like to give some context, to go over the line of thinking that led me to it. Hopefully this’ll also serve to explain why I find the issue so bothersome, and if I’m lucky it might inspire some of you to help me solve it.
People have been saying recently1 that business logic doesn’t belong in controllers. Controllers should be “thin.” They should really only serve to push data around. This data goes to that view, that data is passed to these attributes, that sort of thing. I find myself agreeing with this philosophy; it seems to result in cleaner code all around. Not just in the controller, but also where the logic ends up.
The philosophy is also vocal about where this should be: the model. Models should be “fat.” Using the power of advice2, this is reasonably straightforward. Instead of the controller running this blog post through RedCloth in the show action (which is called when you go to /posts/20), for example, the model runs it through when the render method is called.
This has all sorts of advantages. I can access the rendered content from places other than the one action. If I suddenly have more than twenty readers, I can optimize by pre-rendering the posts and nothing but the model will change. “Thin controllers, fat models” is clearly useful.